package com.handpay.zztong.hp.withdraw.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.config.HttpUrlConstant;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.main.model.limit.LimitBean;
import com.handpay.zztong.hp.main.model.limit.LimitModel;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.ui.WithdrawMoneyDialog;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.withdraw.bean.AvailableWithDrawBean;
import com.handpay.zztong.hp.withdraw.bean.LowestWithDrawBean;
import com.handpay.zztong.hp.withdraw.bean.WithDraw;
import com.handpay.zztong.hp.withdraw.model.AvailableWithDrawModel;
import com.handpay.zztong.hp.withdraw.model.LowestWithDrawModel;
import com.handpay.zztong.hp.withdraw.model.WithDrawModel;

import java.util.Hashtable;

/**
 * 收款提现Activity
 *
 * @author ghwang
 */
public class WithdrawActivity extends ZZTongActivity {

    private Button btnWithdraw = null;
    private Button btnQueryWithdrawRecord = null;
    final static int REQUEST_CODE = 1;
    private Double mMinWithdrawAmount = -1d;
    private Double mMaxWithdrawAmount = -1d;
    private Double sHmoney;
    private LowestWithDrawModel lowestWithDrawModel;
    private AvailableWithDrawModel availableWithDrawModel;
    private WithDrawModel withDrawModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_withdraw);
        super.onCreate(savedInstanceState);
        lowestWithDrawModel = new LowestWithDrawModel(this);
        availableWithDrawModel = new AvailableWithDrawModel(this);
        withDrawModel = new WithDrawModel(this);
//        if (getIntent() != null) {
//            sHmoney = getIntent().getDoubleExtra("money", 0d);
//        }

        sHmoney = (Double) ClientEngine.getInstance().getGlobal("dayTraffic");

        init();
    }

    private void getLowestWithdrawMoney() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("version", ClientEngine.VERSION);
        params.put("platform", ClientEngine.MOBILETYPE);
        params.put("channel", ClientEngine.CHANNEL);
//        doPost(this, Do_GetLowestWithdrawMoney, params, true);
        lowestWithDrawModel.queryLowestWithdraw(HttpUrlConstant.Do_GetLowestWithdrawMoney, params, new BusinessEngineListener<LowestWithDrawBean>() {
            @Override
            public void callbackBusinessResponse(LowestWithDrawBean withDrawBean) {
                mMinWithdrawAmount = Double.valueOf(withDrawBean.getMinAmount());
                mMaxWithdrawAmount = Double.valueOf(withDrawBean.getMaxAmount());
                String tradeDesc = withDrawBean.getTradeDesc();
                if (!TextUtils.isEmpty(tradeDesc)) {
                    ((TextView) findViewById(R.id.tv_trade_desc)).setText(tradeDesc);
                }
                String withdrawDesc = withDrawBean.getWithdrawDesc();
                if (!TextUtils.isEmpty(withdrawDesc)) {
                    ((TextView) findViewById(R.id.tv_withdrawDesc)).setText(withdrawDesc);
                }
            }
        });
    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    @Override
    public ActionBar getActivityActionBar() {
        //leftBar goBack();
        return new ActionBar(this.getString(R.string.withdraw_title), true);
    }

    /**
     * 初始化控制
     */
    private void init() {
        //初始化控件
        btnWithdraw = (Button) findViewById(R.id.startWithdrawBtn);
        btnQueryWithdrawRecord = (Button) findViewById(R.id.queryWithdrawRecordBtn);

        //设置控件属性及事件
        btnWithdraw.setOnClickListener(CommonUtils.createNoQuickResponseViewListener(ZZTConstant.NO_RESPONSE_CLICK_TIME, this));
        btnQueryWithdrawRecord.setOnClickListener(this);
        if (!isMinAndMaxWDInit()) {
            getLowestWithdrawMoney();
        }
        doGetLimit();
    }

    /***
     * 交易限额查询
     */
    private void doGetLimit() {
        if (AccountUtils.getAccountPhone(this) == null) {
            return;
        }
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.PHONE, SecureManager.getInstance().des(AccountUtils.getAccountPhone(this), 1, null));
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(BaseProtocolKey.KEY_APPCODE, BaseProtocolKey.APPCODE_TRANSFER);
        new LimitModel().doLimitPost(this, params, new BusinessEngineListener<LimitBean>() {
            @Override
            public void callbackBusinessResponse(LimitBean bean) {

                String wdPermission = bean.getWdPermission();
                if (null != wdPermission) {
                    AccountUtils.setWDPermission(WithdrawActivity.this, wdPermission);
                }
                if (!AccountUtils.isWDUsable(WithdrawActivity.this)) {
                    btnWithdraw.setEnabled(false);
                    btnWithdraw.setSelected(true);
                }
            }
        });
    }










    /**
     * 判断是否最大提款金额和最小提款金额是否获取到
     *
     * @return false，表示没有获取到。true表示获取到了
     */
    private boolean isMinAndMaxWDInit() {
        //当没拿到数据的时候，重新拿。不可能同时小于0吧！
        return !(0d > mMinWithdrawAmount && 0d > mMaxWithdrawAmount);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.startWithdrawBtn) {
            if (isMinAndMaxWDInit()) {
                /*Intent intent = new Intent(this, WithdrawAmount.class);
                intent.putExtra("minWDAmount", mMinWithdrawAmount.doubleValue());
                intent.putExtra("maxWDAmount", mMaxWithdrawAmount.doubleValue());
                startActivityForResult(intent, REQUEST_CODE);*/

                Hashtable<String, String> params = new Hashtable<String, String>();
                HPLog.e("ZZTongActivity", "ClientEngine.VERSION:" + ClientEngine.VERSION);
                String account = AccountUtils.getAccountName(this);
                params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(account, 1, null));
                params.put("version", ClientEngine.VERSION);
                params.put("platform", ClientEngine.MOBILETYPE);
                params.put("channel", ZZTConfig.UPDATE_CHANNEL);
//                WithdrawActivity.this.doPost(WithdrawActivity.this, DO_GetAvailableWithdrawMoney, params);
                availableWithDrawModel.getAvailableWithDraw(HttpUrlConstant.DO_GetAvailableWithdrawMoney, params, new BusinessEngineListener<AvailableWithDrawBean>() {
                    @Override
                    public void callbackBusinessResponse(AvailableWithDrawBean availableWithDrawBean) {
                        Double money = Double.valueOf(availableWithDrawBean.getAvailableRwdMoney());

                        HPLog.i("WithdrawActivity", "--money-" + money);
                        if (0.0 == money) {
                            Toast.makeText(WithdrawActivity.this, "无可提现余额！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        WithdrawMoneyDialog dialog = new WithdrawMoneyDialog(WithdrawActivity.this, R.style.HPDialog);
                        dialog.initResourse(money, mMinWithdrawAmount, mMaxWithdrawAmount, sHmoney, new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                Double d = (Double) v.getTag();
                                HPLog.i("WithdrawActivity", "money:-- " + d);
                                startWithdraw(d);
                            }
                        });
                    }
                });
            } else {
                //如果没有获取到，重新获取。
                getLowestWithdrawMoney();
            }
        } else if (i == R.id.queryWithdrawRecordBtn) {//启动查询收款记录Activity
            startActivity(new Intent(this, QueryWithdrawRecordsActivity.class));
        } else {
        }
        super.onClick(v);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (REQUEST_CODE == requestCode) {
            if (RESULT_OK == resultCode && null != data) {
                Double amount = data.getDoubleExtra("amount", 0d);
                startWithdraw(amount);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 启动收款提现交易
     */
    public void startWithdraw(Double amount) {
        String account = AccountUtils.getAccountName(this);
        String channel = ClientEngine.CHANNEL;
        Hashtable<String, String> table = new Hashtable<String, String>(2);
        table.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(account, 1, null));
        table.put(BaseProtocolKey.CHANNEL, channel);
        String amountString = "" + Math.round(amount * 100);
        table.put("rwdMoney", SecureManager.getInstance().des(amountString, 1, null));
//        doPost(this, Action_WithDraw, table);
        withDrawModel.withDraw(HttpUrlConstant.DO_WithDraw, table, new BusinessEngineListener<WithDraw>() {
            @Override
            public void callbackBusinessResponse(WithDraw withDraw) {
                String msg = withDraw.getMessage();
                showAlertDialog(WithdrawActivity.this, getString(R.string.tip), msg, false, null);
            }
        });
    }

}
